# -*- coding: utf-8 -*-
import copy
import os
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.mail import send_mail
from django.core.paginator import EmptyPage, InvalidPage, Paginator
from django.db.models.query_utils import Q
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
from django.template.loader import render_to_string
from django.utils.datetime_safe import datetime
from messages.models import Message
from friends.models import FriendshipRequest
from main.forms import UploadImageForm, UserInfoForm, EmailChangeForm, PasswordChangeForm, AddCompanyForm, EditCompanyForm, PartnerForm, WallCommentForm, DiscussionForm, DiscussionMessageForm, GoodForm, OfferForm, OrderForm, ResponseForm, SupportForm, SearchForm, NotifySettingsForm
from main.models import UserInfo, Country, City, Company, GlobalType, Category, Discussion, Good, Offer, Order, ResponseToOrder, NotifySettings
from main.support import has_user_info_if_authenticated, get_common_info
import settings

def index(request, page_id=1):
    """
    Главная
    """
    info  = get_common_info()
    company_list = Company.objects.all()
    paginator = Paginator(company_list, 20)
    try:
        companies = paginator.page(page_id)
    except (EmptyPage, InvalidPage):
        companies = paginator.page(paginator.num_pages)
    return render_to_response("index.html", locals())

@login_required
@has_user_info_if_authenticated
def update_avatar(request):
    """
    Смена аватары пользователя
    """
    form = UploadImageForm(request.POST, request.FILES)
    obj = form.save()
    try:
        ui = request.user.user_info
    except:
        ui = UserInfo()
        ui.last_name = request.user.last_name
        ui.first_name = request.user.first_name
        ui.email = request.user.email
        ui.user = request.user
        ui.save()
    try:
        os.remove(ui.avatar.path)
    except:
        pass

    ui.avatar = copy.deepcopy(obj.image)
    ui.save()
    #obj.delete()
    return HttpResponseRedirect("/userinfo/")




@login_required
def add_userinfo(request):
    '''
    Заполнение информации о пользователе. Оно же настройки-> личное
    '''
    info  = get_common_info()
    user = request.user
    try:
        user_info = user.user_info
    except:
        user_info = None
    if request.method == "GET":
        form = UserInfoForm(instance = user_info)
        return render_to_response("settings_private.html", locals())
    else:
        form = UserInfoForm(request.POST, request.FILES, instance = user_info)
        if form.is_valid():
            country = Country.objects.get(name__iexact=unicode(request.POST.get('country')))
            city = unicode(form.data.get('city'))
            try:
                city = City.objects.filter(country=country).get(name__iexact=city)
            except City.DoesNotExist:
                if city:
                    city = City(name=form.data.get('city'), country=country)
                    city.save()

            user_info = form.save(commit=False)
            if city:
                user_info.city = city
            user_info.country = country
            user_info.user = user
            user_info.save()
            return HttpResponseRedirect("/userinfo/")
        else:
            return render_to_response("settings_private.html", locals())

        
@login_required
@has_user_info_if_authenticated
def main_settings(request):
    """
    настройки -> важное
    """
    info  = get_common_info()
    return render_to_response("settings_main.html", locals())

@login_required
@has_user_info_if_authenticated
def notify_settings(request):
    """
    настройки -> оповещения
    """
    info  = get_common_info()
    if request.method=="GET":
        ns = request.user.notify_settings.all()[0]
        form = NotifySettingsForm(instance = ns)
    else:
        ns = request.user.notify_settings.all()[0]
        form = NotifySettingsForm(request.POST, instance = ns)
        if form.is_valid():
            form.save()
    return render_to_response("settings_notify.html", locals())

@login_required
@has_user_info_if_authenticated
def security_settings(request):
    """
    настройки -> приватности
    """
    info  = get_common_info()
    return render_to_response("settings_security.html", locals())



@login_required
@has_user_info_if_authenticated
def change_email(request):
    """
    смена емейла
    """
    info = get_common_info()
    user = request.user
    form = EmailChangeForm(request.POST)
    if form.is_valid():
        user.email = form.cleaned_data['email']
        user.save()
    return render_to_response("settings_main.html", locals())


@login_required
@has_user_info_if_authenticated
def change_password(request):
    """
    смена пароля
    """
    info = get_common_info()
    user = request.user
    form = PasswordChangeForm(request.POST)
    if form.is_valid():
        if user.check_password(form.cleaned_data['old_password']):
            user.set_password(form.cleaned_data['new_password1'])
            user.save()
        else:
            error_message=u"Неверно указан старый пароль";
    else:
        if not user.check_password(form.data['old_password']):
            error_message=u"Неверно указан старый пароль";

    return render_to_response("settings_main.html", locals())







def user_profile(request, user_id = None):
    """
    страница пользователя
    """
    info  = get_common_info()
    if user_id:
        try:
            user = User.objects.get(id = user_id)
        except User.DoesNotExist:
            user = request.user
    else:
        user = request.user
    return render_to_response("profile.html", locals())

@login_required
@has_user_info_if_authenticated
def friends(request, page_id = 1):
    """
    список друзей
    """
    info  = get_common_info()
    friend_list = request.user.user_info.friends.all()
    paginator = Paginator(friend_list, 20)
    try:
        friends = paginator.page(page_id)
    except (EmptyPage, InvalidPage):
        friends = paginator.page(paginator.num_pages)
    return render_to_response("friends.html", locals())

@login_required
@has_user_info_if_authenticated
def online_friends(request, page_id = 1):
    """
    список друзей онлайн
    """
    info  = get_common_info()
    pre_friend_list = request.user.user_info.friends.all()
    friend_list=[]
    for usr in pre_friend_list:
        if usr.user_info.online():
            friend_list+=[usr]

    paginator = Paginator(friend_list, 20)
    try:
        friends = paginator.page(page_id)
    except (EmptyPage, InvalidPage):
        friends = paginator.page(paginator.num_pages)
    return render_to_response("ofr.html", locals())
    #return render_to_response("friends.html", locals())


@login_required
@has_user_info_if_authenticated
def possible_friends(request, page_id = 1):
    """
    заявки в друзья
    """
    info  = get_common_info()
    friendship_requests = FriendshipRequest.objects.filter(to_user = request.user)
    return render_to_response("possible_friends.html", locals())


def users(request, page_id = 1):
    """
    список пользователей
    """
    info  = get_common_info()
    user_list = User.objects.filter(is_active = True)
    paginator = Paginator(user_list, 20)
    try:
        users = paginator.page(page_id)
    except (EmptyPage, InvalidPage):
        users = paginator.page(paginator.num_pages)
    return render_to_response("users.html", locals())


def online_users(request, page_id = 1):
    """
    список пользователей онлайн
    """
    info  = get_common_info()
    pre_user_list = User.objects.filter(is_active = True)
    user_list=[]
    for usr in pre_user_list:
        if usr.user_info.online:
            user_list+=[usr]

    paginator = Paginator(user_list, 20)
    try:
        users = paginator.page(page_id)
    except (EmptyPage, InvalidPage):
        users = paginator.page(paginator.num_pages)
    return render_to_response("online_users.html", locals())


def companies(request, page_id = 1):
    """
    список компаний
    """
    info  = get_common_info()
    company_list = Company.objects.all()
    paginator = Paginator(company_list, 20)
    try:
        companies = paginator.page(page_id)
    except (EmptyPage, InvalidPage):
        companies = paginator.page(paginator.num_pages)
    return render_to_response("companies.html", locals())


def companies_online(request, page_id = 1):
    """
    список компаний онлайн(тех, чьи администраторы сейчас онлайн)
    """
    info  = get_common_info()
    pre_company_list = Company.objects.all()
    company_list = []
    for company in pre_company_list:
        if company.owner.user_info.online():
            company_list+=[company]
    paginator = Paginator(company_list, 20)
    try:
        companies = paginator.page(page_id)
    except (EmptyPage, InvalidPage):
        companies = paginator.page(paginator.num_pages)
    return render_to_response("online_companies.html", locals())





@login_required
@has_user_info_if_authenticated
def add_company(request):
    """
    регистрация новой компании
    """
    info  = get_common_info()
    if request.method=="GET":
        form = AddCompanyForm()
        return render_to_response("register_company.html", locals())
    else:
        form = AddCompanyForm(request.POST, request.FILES)
        if form.is_valid():
            company = form.save(commit=False)
            company.type = GlobalType.objects.get(name__iexact=settings.GLOBAL_TYPE)
            company.owner = request.user
            company.save()
            company.categories = form.cleaned_data["categories"]
            company.save()
            for user in User.objects.all():
                try:
                    user.notify_settings.all()[0].send_notify_new_companies(company)
                except:
                    pass
            return HttpResponseRedirect("/edit_company/%s/"%company.id)
        else:
            return render_to_response("register_company.html", locals())


@login_required
@has_user_info_if_authenticated
def edit_company(request, company_id):
    """
    редактирование информации о компании
    """
    info  = get_common_info()
    try:
        company = Company.objects.get(id = company_id)
    except:
        raise Http404
    if company.owner != request.user:
        raise Http404

    if request.method=="GET":
        form = EditCompanyForm(instance = company)
        return render_to_response("edit_company.html", locals())
    else:
        form = EditCompanyForm(request.POST, request.FILES, instance = company)
        if form.is_valid():
            company = form.save(commit=False)
            country = Country.objects.get(name__iexact=unicode(request.POST.get('country')))
            city = unicode(form.data.get('city'))
            try:
                city = City.objects.filter(country=country).get(name__iexact=city)
            except City.DoesNotExist:
                if city:
                    city = City(name=form.data.get('city'), country=country)
                    city.save()
            if city:
                company.city = city
            company.country = country
            company.activities = form.cleaned_data["activities"]
            company.categories = form.cleaned_data["categories"]
            company.save()
        else:
            return render_to_response("edit_company.html", locals())
    return HttpResponseRedirect("/edit_company/%s/"%company.id)

@login_required
@has_user_info_if_authenticated
def dialog(request, username):
    """
    диалог с заданным пользователем
    """
    info  = get_common_info()
    try:
        usr = User.objects.get(username = username)
        me = request.user
    except:
        raise Http404
    message_list = Message.objects.filter(Q(sender=usr, recipient=me) | Q(sender=me, recipient=usr)).order_by("-id")[:20]
    message_list=message_list[::-1]
    return render_to_response("dialog.html", locals())



def check_new_messages(request, me_id=None, usr_id=None):
    """
    аяксовский метод, проверка свежих сообщений
    """
    if request.method=="POST":
        raise Http404
    try:
        me = User.objects.get(id =me_id)
        usr = User.objects.get(id = usr_id)
    except:
        raise Http404
    message_list = Message.objects.filter(Q(sender=usr, recipient=me, read_at__isnull = True)).order_by("-id")
    if len(message_list) ==0:
        message_list = Message.objects.filter(Q(sender=me, recipient=usr, read_at__isnull = True)).order_by("-id")
    for message in message_list:
        message.read_at = datetime.now()
        message.save()
    return render_to_response("message.html", locals())



@login_required
@has_user_info_if_authenticated
def post_message_ajax(request):
    """
    аяксовский метод, добавление сообщения
    """
    try:
        subject = request.user.username
        sender = request.user
        recipient = User.objects.get(username = request.POST["user_to"])
        body = request.POST["message_text"]
        msg = Message(subject = subject, body = body, sender = sender, recipient = recipient)
        msg.save()
        message_list = Message.objects.filter(id = msg.id)
        return render_to_response("message.html", locals())
    except:
        raise Http404


def company(request, company_id):
    """
    страница компании
    """
    info  = get_common_info()
    try:
        company = Company.objects.get(id = company_id)
    except:
        raise Http404
    return render_to_response("company.html", locals())

@login_required
@has_user_info_if_authenticated
def add_to_companies(request, company_id):
    """
    добавление компании в список избранных
    """
    try:
        company = Company.objects.get(id = company_id)
    except:
        raise Http404
    if not request.user in company.users.all():
        company.users.add(request.user)
        company.save()
    return HttpResponseRedirect("/company/%s/"%company.id)
    #return render_to_response("company.html", locals())

@login_required
@has_user_info_if_authenticated
def delete_from_company(request, company_id):
    """
    удаление компании из списка избранных
    """
    try:
        company = Company.objects.get(id = company_id)
    except:
        raise Http404
    if request.user in company.users.all():
        company.users.remove(request.user)
        company.save()
    return HttpResponseRedirect("/company/%s/"%company.id)

@login_required
@has_user_info_if_authenticated
def add_partner(request, company_id):
    """
    добавление партнера (через вставку ссылки)
    """
    info  = get_common_info()
    try:
        company = Company.objects.get(id = company_id)
    except:
        raise Http404
    if not request.user == company.owner:
        raise Http404
    if request.method == "GET":
        form = PartnerForm()
        return render_to_response("add_partner.html", locals())
    else:
        form = PartnerForm(request.POST)
        if not request.user == company.owner:
            raise Http404

        if form.is_valid():
            partner_id = int(form.cleaned_data["partner_url"])
            try:
                partner = Company.objects.get(id = partner_id)
                company = Company.objects.get(id = company_id)
                company.partners.add(partner)
                company.save()
            except:
                pass
        else:
            return render_to_response("add_partner.html", locals())
        return HttpResponseRedirect("/add_partner/%s" %company.id)




@login_required
@has_user_info_if_authenticated
def delete_partner(request, company_id, partner_id):
    """
    удаление партнера
    """
    try:
        company = Company.objects.get(id = company_id)
    except:
        raise Http404
    if not request.user == company.owner:
        raise Http404
    try:
        partner = Company.objects.get(id = partner_id)
        company.partners.remove(partner)
        company.save()
    except:
        pass
    return HttpResponseRedirect("/add_partner/%s" %company.id)



def user_companies(request, user_id, page_id = 1):
    """
    Компании, зарегистрированные пользователем
    """
    info  = get_common_info()
    try:
        usr = User.objects.get(id = user_id)
    except:
        raise Http404
    company_list = Company.objects.filter(owner = usr)
    paginator = Paginator(company_list, 20)
    try:
        companies = paginator.page(page_id)
    except (EmptyPage, InvalidPage):
        companies = paginator.page(paginator.num_pages)
    return render_to_response("user_companies.html", locals())


def by_category(request, category_id, page_id = 1):
    """
    Компании по категориям
    """
    info  = get_common_info()
    try:
        category = Category.objects.get(id = category_id, type__name__iexact=settings.GLOBAL_TYPE)
    except:
        raise Http404
    company_list = category.category_companies.all()
    paginator = Paginator(company_list, 20)
    try:
        companies = paginator.page(page_id)
    except (EmptyPage, InvalidPage):
        companies = paginator.page(paginator.num_pages)
    #return render_to_response("companies.html", locals())
    return render_to_response("index.html", locals())

@login_required
@has_user_info_if_authenticated
def post_wall_comment(request):
    """
    Запостить коммент на стену
    """
    form = WallCommentForm(request.POST)
    if form.is_valid():
        cmt = form.save()
        user = cmt.recipient
        try:
            user.notify_settings.all()[0].send_notify_wall_comments(cmt)
        except:
            pass
    return HttpResponseRedirect("/profile/%s/"%form.data["recipient"])

@login_required
@has_user_info_if_authenticated
def all_dialogs(request):
    """
    Все диалоги пользователя
    """
    me = request.user
    sent_messages = Message.objects.filter(recipient=me)
    received_messages = Message.objects.filter(sender=me)
    dialog_users = []
    for msg in sent_messages:
        if not msg.sender in dialog_users:
            dialog_users+=[msg.sender]
    for msg in received_messages:
        if not msg.recipient in dialog_users:
            dialog_users+=[msg.recipient]
    info  = get_common_info()
    return render_to_response("dialogs.html", locals())

@login_required
@has_user_info_if_authenticated
def discussion(request, discussion_id):
    """
    Обсуждение
    """
    try:
        discussion = Discussion.objects.get(id = discussion_id)
    except:
        pass
    info  = get_common_info()
    return render_to_response("discussion.html", locals())


@login_required
@has_user_info_if_authenticated
def discussions(request, page_id = 1):
    """
    все обсуждения
    """
    info  = get_common_info()
    discussion_list = Discussion.objects.filter(type__name__iexact=settings.GLOBAL_TYPE)
    paginator = Paginator(discussion_list, 20)
    try:
        discussions = paginator.page(page_id)
    except (EmptyPage, InvalidPage):
        discussions = paginator.page(paginator.num_pages)
    return render_to_response("discussions.html", locals())

@login_required
@has_user_info_if_authenticated
def start_discussion(request):
    """
    начать обсуждение
    """
    if request.method == "GET":
        return HttpResponseRedirect("/discussions/")
    else:
        form = DiscussionForm(request.POST)
        if form.is_valid():
            discussion = form.save(commit = False)
            discussion.type =  GlobalType.objects.get(name__iexact = settings.GLOBAL_TYPE)
            discussion.creator = request.user
            discussion.save()
            return HttpResponseRedirect("/discussion/%s/"%discussion.id)
        else:
            return HttpResponseRedirect("/discussions/")

@login_required
@has_user_info_if_authenticated
def post_discussion_message(request, discussion_id):
    """
    Запостить сообщение в обсуждение
    """
    if request.method == "GET":
        raise Http404
    try:
        discussion = Discussion.objects.get(id = discussion_id)
    except:
        raise Http404
    form = DiscussionMessageForm(request.POST)
    if form.is_valid():
        dm = form.save(commit = False)
        dm.publisher = request.user
        dm.post_date = datetime.now()
        dm.save()
        discussion.messages.add(dm)
        discussion.save()
    return HttpResponseRedirect("/discussion/%s/"%discussion_id)


def all_clients(request, company_id, page_id= 1):
    """
    все клиенты компании
    """
    info  = get_common_info()
    try:
        company = Company.objects.get(id = company_id)
    except:
        raise Http404
    user_list = company.users.all()
    paginator = Paginator(user_list, 20)
    try:
        users = paginator.page(page_id)
    except (EmptyPage, InvalidPage):
        users = paginator.page(paginator.num_pages)
    return render_to_response("clients.html", locals())



def all_partners(request, company_id, page_id = 1):
    """
    все партнеры компании
    """
    info  = get_common_info()
    try:
        company = Company.objects.get(id = company_id)
    except:
        raise Http404
    company_list = company.partners.all()
    paginator = Paginator(company_list, 20)
    try:
        companies = paginator.page(page_id)
    except (EmptyPage, InvalidPage):
        companies = paginator.page(paginator.num_pages)
    return render_to_response("partners.html", locals())



def showcase(request, company_id, page_id = 1):
    """
    витрина компании
    """
    info  = get_common_info()
    try:
        company = Company.objects.get(id = company_id)
    except:
        raise Http404
    good_list = company.goods.all()
    paginator = Paginator(good_list, 20)
    try:
        goods = paginator.page(page_id)
    except (EmptyPage, InvalidPage):
        goods = paginator.page(paginator.num_pages)
    return render_to_response("showcase.html", locals())

@login_required
@has_user_info_if_authenticated
def add_good(request, company_id):
    """
    добавить товар
    """
    info  = get_common_info()
    try:
        company = Company.objects.get(id = company_id)
    except:
        raise Http404
    if company.owner != request.user:
        raise Http404
    if request.method=="GET":
        form = GoodForm()
    else:
        form = GoodForm(request.POST, request.FILES)
        if form.is_valid():
            good = form.save(commit = False)
            good.company = company
            good.save()
    return render_to_response("edit_good.html", locals())

@login_required
@has_user_info_if_authenticated
def edit_good(request, good_id):
    """
    редактировать товар
    """
    info  = get_common_info()
    try:
        good = Good.objects.get(id = good_id)
        company = good.company
    except:
        raise Http404
    if good.company.owner != request.user:
        raise Http404
    if request.method=="GET":
        form = GoodForm(instance=good)
    else:
        form = GoodForm(request.POST, request.FILES, instance=good)
        if form.is_valid():
            good = form.save()
    return render_to_response("edit_good.html", locals())


def offers(request, page_id = 1):
    """
    предложения
    """
    info  = get_common_info()
    offer_list = Offer.objects.filter(company__type__name__iexact=settings.GLOBAL_TYPE).order_by("-id")
    paginator = Paginator(offer_list, 20)
    try:
        offers = paginator.page(page_id)
    except (EmptyPage, InvalidPage):
        offers = paginator.page(paginator.num_pages)
    return render_to_response("offers.html", locals())



@login_required
@has_user_info_if_authenticated
def create_offer(request, company_id):
    """
    создать предложение
    """
    info  = get_common_info()
    try:
        company = Company.objects.get(id = company_id)
    except:
        raise Http404
    if company.owner != request.user:
        raise Http404
    if request.method=="GET":
        form = OfferForm()
        return render_to_response("edit_offer.html", locals())
    else:
        form = OfferForm(request.POST)
        if form.is_valid():
            offer = form.save(commit = False)
            offer.company = company
            offer.save()
            return HttpResponseRedirect("/company/%s/"%company.id)
        else:
            return render_to_response("edit_offer.html", locals())

@login_required
@has_user_info_if_authenticated
def edit_offer(request, offer_id):
    """
    редактировать предложение
    """
    info  = get_common_info()
    try:
        offer = Offer.objects.get(id = offer_id)
    except:
        raise Http404
    if offer.company.owner != request.user:
        raise Http404
    if request.method=="GET":
        form = OfferForm(instance = offer)
        return render_to_response("edit_offer.html", locals())
    else:
        form = OfferForm(request.POST, instance = offer)
        if form.is_valid():
            offer = form.save()
            return HttpResponseRedirect("/company/%s/"%company.id)
        else:
            return render_to_response("edit_offer.html", locals())

@login_required
@has_user_info_if_authenticated
def company_offers(request, company_id, page_id = 1):
    """
    все предложение компании
    """
    info  = get_common_info()
    try:
        company = Company.objects.get(id = company_id)
    except:
        raise Http404
    offer_list = company.offers.all().order_by("-id")
    paginator = Paginator(offer_list, 20)
    try:
        offers = paginator.page(page_id)
    except (EmptyPage, InvalidPage):
        offers = paginator.page(paginator.num_pages)
    return render_to_response("company_offers.html", locals())





@login_required
@has_user_info_if_authenticated
def delete_offer(request, offer_id):
    """
    удалить предложение
    """
    info  = get_common_info()
    try:
        offer = Offer.objects.get(id = offer_id)
    except:
        raise Http404
    if offer.company.owner != request.user:
        raise Http404
    offer.delete()
    return HttpResponseRedirect("/company/%s/"%company.id)


@login_required
@has_user_info_if_authenticated
def orders(request, page_id = 1):
    """
    заказы
    """
    info  = get_common_info()
    order_list = Order.objects.filter(type__name__iexact=settings.GLOBAL_TYPE).order_by("-id")
    paginator = Paginator(order_list, 20)
    try:
        orders = paginator.page(page_id)
    except (EmptyPage, InvalidPage):
        orders = paginator.page(paginator.num_pages)
    return render_to_response("orders.html", locals())

@login_required
@has_user_info_if_authenticated
def create_order(request):
    """
    создать заказ
    """
    info  = get_common_info()
    if request.method=="GET":
        form = OrderForm()
        return render_to_response("edit_order.html", locals())
    else:
        form = OrderForm(request.POST)
        if form.is_valid():
            order = form.save(commit = False)
            order.user = request.user
            order.type = GlobalType.objects.get(name__iexact=settings.GLOBAL_TYPE)
            order.save()
            return HttpResponseRedirect("/order/%s/"%order.id)
        else:
            return render_to_response("edit_order.html", locals())

@login_required
@has_user_info_if_authenticated
def edit_order(request, order_id):
    """
    редактировать заказ
    """
    info  = get_common_info()
    try:
        order = Order.objects.get(id = order_id)
    except:
        raise Http404
    if order.user != request.user:
        raise Http404
    if request.method=="GET":
        form = OrderForm(instance = order)
        return render_to_response("edit_order.html", locals())
    else:
        form = OrderForm(request.POST, instance=order)
        if form.is_valid():
            order = form.save()
            order.order_date = datetime.now()
            order.save()
            return HttpResponseRedirect("/order/%s/"%order.id)
        else:
            return render_to_response("edit_order.html", locals())


@login_required
@has_user_info_if_authenticated
def show_order(request, order_id):
    """
    показать заказ
    """
    info  = get_common_info()
    try:
        order = Order.objects.get(id = order_id)
    except:
        raise Http404
    return render_to_response("order.html", locals())


@login_required
@has_user_info_if_authenticated
def response_to_order(request, order_id):
    """
    ответить на заказ
    """
    info  = get_common_info()
    try:
        order = Order.objects.get(id = order_id)
    except:
        raise Http404
    if request.method =="GET":
        return render_to_response("response_to_order.html", locals())
    else:
        form = ResponseForm(request.POST)
        if form.is_valid():
            resp = form.save(commit = False)
            resp.order = order
            resp.response_date = datetime.now()
            resp.active = True
            resp.save()
            return HttpResponseRedirect("/order/%s/"%order.id)
        else:
            return render_to_response("response_to_order.html", locals())

@login_required
@has_user_info_if_authenticated
def decline_executor(request, response_id):
    try:
        resp = ResponseToOrder.objects.get(id = response_id)
    except:
        raise Http404
    if resp.order.user == request.user:
        resp.decline()
    return HttpResponseRedirect('/order/%s/'%resp.order.id)

@login_required
@has_user_info_if_authenticated
def accept_executor(request, response_id):
    try:
        resp = ResponseToOrder.objects.get(id = response_id)
    except:
        raise Http404
    if resp.order.user == request.user:
        resp.accept()
        other_responses = resp.order.responses.exclude(id = response_id)
        for o in other_responses:
            o.decline()
    return HttpResponseRedirect('/order/%s/'%resp.order.id)



def make_notify_settings(request):
    pass
    #for usr in User.objects.all():
    #        ns = NotifySettings(user = usr, notify_friends = True, notify_order_response = True, notify_new_companies = True, notify_wall_comments = True)
    #        ns.save()


def support(request):
    info  = get_common_info()
    if request.method == "GET":
        form = SupportForm()
        return render_to_response("support.html", locals())
    else:
        form = SupportForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data["email"]
            subj = u"Сообщение от "+email
            text = form.cleaned_data["text"]
            try:
                send_mail(subj, text, email,(settings.CLIENT_EMAIL,), fail_silently=True)
                message = u"Сообщение отправлено"
            except:
                pass
        return render_to_response("support.html", locals())

def search(request):
    info  = get_common_info()
    if request.method == "GET":
        raise Http404
    form = SearchForm(request.POST)
    if form.is_valid():
        search_q = form.cleaned_data["search_q"]
        type=form.cleaned_data["where_to_look"]
        if type==u"1":
            user_list = User.objects.filter(Q(last_name__icontains=search_q) | Q(first_name__icontains=search_q))
            paginator = Paginator(user_list, 20)
            try:
                users = paginator.page(1)
            except (EmptyPage, InvalidPage):
                users = paginator.page(paginator.num_pages)
            return render_to_response("users.html", locals())
        if type==u"2":
            company_list = Company.objects.filter(name__icontains=search_q, type__name__iexact=settings.GLOBAL_TYPE)
            paginator = Paginator(company_list, 20)
            try:
                companies = paginator.page(1)
            except (EmptyPage, InvalidPage):
                companies = paginator.page(paginator.num_pages)
            return render_to_response("companies.html", locals())
        if type==u"3":
            discussion_list = Discussion.objects.filter(subj__icontains=search_q, type__name__iexact=settings.GLOBAL_TYPE)
            paginator = Paginator(discussion_list, 20)
            try:
                discussions = paginator.page(1)
            except (EmptyPage, InvalidPage):
                discussions = paginator.page(paginator.num_pages)
            return render_to_response("discussions.html", locals())
        if type==u"4":
            offer_list = Offer.objects.filter(text__icontains=search_q, company__type__name__iexact=settings.GLOBAL_TYPE).order_by("-id")
            paginator = Paginator(offer_list, 20)
            try:
                offers = paginator.page(1)
            except (EmptyPage, InvalidPage):
                offers = paginator.page(paginator.num_pages)
            return render_to_response("offers.html", locals())
        if type==u"5":
            order_list = Order.objects.filter(subj__icontains=search_q, type__name__iexact=settings.GLOBAL_TYPE).order_by("-id")
            paginator = Paginator(order_list, 20)
            try:
                orders = paginator.page(1)
            except (EmptyPage, InvalidPage):
                orders = paginator.page(paginator.num_pages)
            return render_to_response("orders.html", locals())
    else:
        return HttpResponseRedirect("/")

